package com.example.feidaolumanager.pages

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.paint
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import com.example.feidaolumanager.Constants
import com.example.feidaolumanager.MyTextField
import com.example.feidaolumanager.R
import com.example.feidaolumanager.pages.ui.theme.FeidaoluManagerTheme
import com.example.feidaolumanager.pojo.RegisterDTO
import com.example.feidaolumanager.viewModel.AgentViewModel
import com.example.feidaolumanager.viewModel.LoginViewModel

class RegisterActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // init object
        val agentViewModel = ViewModelProvider(this)[AgentViewModel::class.java]
        val loginViewModel = ViewModelProvider(this)[LoginViewModel::class.java]

        // init data
        agentViewModel.getAgents()



        setContent {
            FeidaoluManagerTheme {
                var account by remember {
                    mutableStateOf("")
                }
                var password by remember {
                    mutableStateOf("")
                }
                var name by remember {
                    mutableStateOf("")
                }
                var role by remember {
                    mutableStateOf("")
                }
                var agent by remember {
                    mutableStateOf("")
                }

                // init observe
                loginViewModel.registerResponse.observe(this) {
                    if (it != null) {
                        if (it.code == Constants.success_code) {
                            Toast.makeText(this, "注册成功", Toast.LENGTH_LONG).show()
                            account = ""
                            password = ""
                            role = ""
                            agent = ""
                        } else {
                            Toast.makeText(this, "注册失败:${it.msg}", Toast.LENGTH_LONG).show()
                        }
                    }
                }

                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    if (agentViewModel.agentState.errorMsg == null) {
                        Column(
                            modifier = Modifier
                                .fillMaxSize()
                                .paint(
                                    painterResource(id = R.drawable.bg),
                                    contentScale = ContentScale.FillBounds
                                ),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {


                            Spacer(modifier = Modifier.height(100.dp))

                            Image(
                                modifier = Modifier
                                    .height(50.dp)
                                    .width(50.dp),
                                painter = painterResource(id = R.drawable.jxyd),
                                contentDescription = "公司logo"
                            )
                            Text(
                                text = "非道路机械管理平台",
                                modifier = Modifier,
                                color = Color.White,
                                fontSize = 20.sp
                            )


                            var accountErrorMsg by remember {
                                mutableStateOf("")
                            }

                            MyTextField(
                                label = "账号",
                                field = account,
                                errorMsg = accountErrorMsg
                            ) {
                                account = it
                            }

                            var passwordErrorMsg by remember {
                                mutableStateOf("")
                            }

                            MyTextField(
                                label = "密码",
                                field = password,
                                errorMsg = passwordErrorMsg
                            ) {
                                password = it
                            }

                            var nameErrorMsg by remember {
                                mutableStateOf("")
                            }

                            MyTextField(
                                label = "姓名",
                                field = name,
                                errorMsg = nameErrorMsg,
                                onFieldChange = {
                                    name = it
                                })


                            val roles = listOf("施工方", "街道办", "住建局", "环保局")


                            var roleErrorMsg by remember {
                                mutableStateOf("")
                            }


                            var agentErrorMsg by remember {
                                mutableStateOf("")
                            }

                            // 下拉选择身份角色
                            MyDropdownSelected("角色", role, roleErrorMsg, roles) {
                                role = it
                            }

                            // 下拉按钮选择代理商
                            MyDropdownSelected(
                                "所属",
                                agent,
                                agentErrorMsg,
                                agentViewModel.agentState.agents_name
                            ) {
                                agent = it
                            }

                            // 注册按钮
                            Button(onClick = {
                                // 验证通过后登录
                                accountErrorMsg = if (account.isEmpty()) {
                                    "账号不能为空！"
                                } else {
                                    ""
                                }

                                passwordErrorMsg = if (password.isEmpty()) {
                                    "密码不能为空"
                                } else {
                                    ""
                                }

                                roleErrorMsg = if (role.isEmpty()) {
                                    "角色不能为空"
                                } else {
                                    ""
                                }

                                agentErrorMsg = if (agent.isEmpty()) {
                                    "请选择一个代理商"
                                } else {
                                    ""
                                }

                                nameErrorMsg = if (name.isEmpty()) {
                                    "用户名不能为空"
                                } else {
                                    ""
                                }

                                if (accountErrorMsg.isEmpty() && passwordErrorMsg.isEmpty() && roleErrorMsg.isEmpty() && agentErrorMsg.isEmpty()
                                    && nameErrorMsg.isEmpty()
                                ) {
                                    // 验证通过调用登录接口

                                    Log.i(this.toString(), "用户名：$account, 密码:$password")

                                    loginViewModel.register(
                                        RegisterDTO(
                                            account,
                                            password,
                                            roles.indexOf(role) + 1,
                                            agentViewModel.agentState.agents?.get(
                                                agentViewModel
                                                    .agentState.agents_name?.indexOf(agent)
                                                    ?: 0
                                            )?.id ?: 0,
                                            name
                                        )
                                    )
                                }
                            }) {
                                Text(text = "注册")
                            }


                            Button(
                                onClick = {
                                    // 点击跳转到注册界面
                                    finish()
                                },
                                colors = ButtonDefaults.buttonColors(containerColor = Color.Transparent)
                            ) {
                                Text(text = "返回登录")
                            }
                        }
                    } else {
                        Text(
                            text = agentViewModel.agentState.errorMsg!!,
                            color = Color.Red,
                            textAlign = TextAlign.Center
                        )
                    }

                }
            }
        }
    }

    @Composable
    @OptIn(ExperimentalMaterial3Api::class)
    private fun MyDropdownSelected(
        label: String,
        field: String,
        errorMsg: String,
        roles: List<String>?,
        onSelected: (String) -> Unit
    ) {

        var ifShow by remember {
            mutableStateOf(false)
        }

        TextField(
            value = field,
            onValueChange = {

            },
            enabled = false,
            modifier = Modifier
                .clickable {
                    // 点击显示下拉框
                    ifShow = true
                }
                .background(color = Color.Transparent)
                .fillMaxWidth(),
            colors = TextFieldDefaults.colors(
                unfocusedContainerColor = Color.Transparent,
            ),
            label = {
                Text(label)
            }, textStyle = TextStyle(color = Color.Black),
            placeholder = {
                Text(text = "点击选择${label}")
            }
        )
        Text(
            modifier = Modifier
                .fillMaxWidth()
                .padding(start = 50.dp),
            text = errorMsg,
            color = Color.Red
        )
        // 下拉按钮选择身份
        Box(modifier = Modifier) {
            DropdownMenu(
                expanded = ifShow,
                onDismissRequest = { ifShow = false }, modifier = Modifier.fillMaxWidth()
            ) {
                roles?.forEach {
                    DropdownMenuItem(text = {
                        Text(text = it, modifier = Modifier.fillMaxWidth())
                    }, onClick = {
                        onSelected(it)
                        ifShow = false
                    }, modifier = Modifier.fillMaxWidth())
                }
            }
        }
    }
}
